package utils

import (
	"fmt"
	"strings"
)

// DEMO定义分布结构体
type Distribution struct {
	ProvinceDistribution map[string]int `json:"province_distribution"`
	AgeDistribution      map[string]int `json:"age_distribution"`
}

// 将分布数据解析为 map[string]int
func ParseDistribution(data []string) (map[string]int, error) {
	result := make(map[string]int)
	for i, line := range data {
		if i == 0 { // 跳过表头
			continue
		}
		fmt.Println(line)
		parts := strings.Split(line, "|")
		fmt.Println(line, " len of parts", len(parts), " ", parts)
		if len(parts) < 2 {
			continue
			// return nil, fmt.Errorf("invalid line format: %s", line)
		}
		key := parts[0] // 分布的 key (如省份或年龄)
		value := 0
		_, err := fmt.Sscanf(parts[1], "%d", &value)
		if err != nil {
			return nil, fmt.Errorf("failed to parse value in line: %s, error: %v", line, err)
		}
		result[key] = value
	}
	return result, nil
}

// 整合分布并转换为 JSON
func IntegrateDistributions(provinceData, ageData []string) (*Distribution, error) {
	// 解析省份分布
	provinceDist, err := ParseDistribution(provinceData)
	if err != nil {
		return nil, fmt.Errorf("failed to parse province distribution: %v", err)
	}

	// 解析年龄分布
	ageDist, err := ParseDistribution(ageData)
	if err != nil {
		return nil, fmt.Errorf("failed to parse age distribution: %v", err)
	}

	// 构建 Distribution 结构体
	distribution := &Distribution{
		ProvinceDistribution: provinceDist,
		AgeDistribution:      ageDist,
	}

	// 转换为 JSON
	// jsonData, err := json.MarshalIndent(distribution, "", "  ")
	// if err != nil {
	// 	return "", fmt.Errorf("failed to encode JSON: %v", err)
	// }

	return distribution, nil
}

func ReplaceSQLPlaceholders(sqlQuery string, results []string) string {
	// 将 []string 转换为 SQL 格式化的字符串列表
	placeholders := "'" + strings.Join(results, "', '") + "'"

	// 替换 SQL 中的占位内容
	return strings.Replace(sqlQuery, "('101', '102', '103', '104', '105')", "("+placeholders+")", 1)
}
